import IPConfig from '@/constants/IPConfig'
import { utils, writeFile } from 'xlsx'
export const exportExcel = (columns, data, filename) => {
  const book = utils.book_new()
  const sheet = utils.json_to_sheet(transformDataKeyByColumns(columns, data))
  utils.book_append_sheet(book, sheet, 'Sheet')
  writeFile(book, `${filename}.xlsx`)
}

const transformDataKeyByColumns = (columns, data) => {
  const keyMap = columns.reduce((pre, item) => {
    if (item.children) {
      item.children.forEach((item) => {
        if (item.dataIndex) {
          pre[item.dataIndex] = item.title
        }
      })
    } else if (item.dataIndex) {
      pre[item.dataIndex] = item.title
    }
    return pre
  }, {})
  return data.map((item) => {
    return Object.entries(item).reduce((pre, [key, value]) => {
      if (keyMap[key]) {
        pre[keyMap[key]] = value
      }
      return pre
    }, {})
  })
}

export const downLoadFileFunc = () => {
  console.log('1234')
  const link = document.createElement('a')
  // link.href = window.location.origin + '/assets/enterprise.xlsx'
  // link.href = window.location.hostname + '/leaderboard/excel/exportExcel?fileName=%E4%BC%81%E4%B8%9A%E5%91%98%E5%B7%A5%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF'
  link.href = `${IPConfig.projectIP}/leaderboard/excel/exportExcel?fileName=enterprise_20240607`

  link.href = `https://wtjhcdn.cnvct.cn/client_resource/enterprise_20240607.xlsx`

  console.log('link.href', link.href)
  link.setAttribute('download', `企业员工导入模板.xlsx`)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

export const downLoadFileFuncCampus = () => {
  console.log('1234')
  const link = document.createElement('a')

  link.href = `${IPConfig.projectIP}/leaderboard/campus/excel/exportExcel?fileName=campus_20240607`

  link.href = `https://wtjhcdn.cnvct.cn/client_resource/campus_20240607.xlsx`
  link.setAttribute('download', `校园学员导入模板.xlsx`)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
